What is the difference between a regular function and an arrow function on binding to "this"?
What is the difference between a regular function and an arrow function on binding to "this"?
445
15-May-2023
Updated on 15-May-2023
Aryan Kumar
15-May-2023The main difference between a regular function and an arrow function is how they bind to the this keyword.
A regular function binds this to the object that it is called on. For example, if you call a regular function from an object, this will refer to that object.
An arrow function, on the other hand, binds this to the value of this at the time the arrow function is defined. This means that an arrow function always has the same value of this, regardless of how it is called.
Here is an example of how regular functions and arrow functions bind to this:
Code snippet
As you can see, the regular function logs the object that it is called on, while the arrow function logs the global object.
This difference in how regular functions and arrow functions bind to this can be important to keep in mind when you are writing JavaScript code.